﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Nirvana
{
    public static class CameraExtensions
    {
        public static bool SnapShoot(this Camera camera,string path)
        {
            RenderTexture targetTexture = camera.targetTexture;
            if (targetTexture == null) return false;
            RenderTexture.active = targetTexture;
            var img = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.RGBA32, false);
            img.hideFlags = HideFlags.HideAndDontSave;
            img.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height),0,0);
            img.Apply();
            RenderTexture.active = null;

            try
            {
                byte[] bytes = img.EncodeToPNG();
                FileStream stream = File.OpenWrite(path);
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
            }catch(Exception ex)
            {
                Debug.LogError(ex.Message);
                return false;
            }
            finally
            {
                GameObject.DestroyImmediate(img);
            }
            return true;
        }

    }
}

